package com.apobates.forum.thrones.admin.controller;

import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.entity.TopicTag;
import com.apobates.forum.core.entity.proxy.TopicReplica;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.core.service.TopicTagService;
import com.apobates.forum.event.elderly.ActionEventCulpritor;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.admin.controller.form.TopicTagForm;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.StringSeekUtils;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;

/**
 * 话题标签控制器
 *
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/topic/tag")
public class AdminTopicTagController {
    @Autowired
    private TopicTagService topicTagService;
    @Autowired
    private TopicService topicService;
    @Value("${site.pageSize}")
    private int pageSize;
    
    @GetMapping(path = "/")
    public String listPage(
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            HttpServletRequest request,
            Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/topic/tag/").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<TopicTag> rs = topicTagService.getAll(pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/topic_tag/index";
    }
    
    //删除话题标签的关联
    @PostMapping(path = "/delete", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage deleteTagRelativeAction(
            @RequestParam("id") long tagId,
            @RequestParam("topic") long topicId,
            @RequestParam(value = "token", required = false, defaultValue = "0") String token,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        ActionEventCulpritor aec = AdminHomeController.getActionCulpritor(mbean.getMid(), mbean.getNickname(), request, token);
        return TipMessage.Builder.take(()->topicTagService.deleteForTopic(topicId, tagId, aec)).success("成功删除标签").error("操作失败");
    }
    
    @GetMapping(path = "/collection")
    public String topicTaglistPage(
            @RequestParam("topic") long topicId,
            HttpServletRequest request,
            Model model) {
        model.addAttribute("rs", topicTagService.getAllBy(topicId));
        return "admin/topic_tag/topic";
    }
    
    //为话题新增标签
    @GetMapping(path = "/create")
    public String createTopicTagForm(
            @RequestParam("topic") long topicId,
            HttpServletRequest request,
            Model model) {
        Topic topic = topicService.get(topicId).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
        //
        TopicTagForm form = new TopicTagForm();
        form.setTopic(topicId);
        form.setTitle(topic.getTitle());
        model.addAttribute("form", form);
        return "admin/topic_tag/topic_edit";
    }
    
    @PostMapping(path = "/create")
    public String createTopicTagAction(
            @ModelAttribute("form") TopicTagForm form,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        //过滤一下
        String newTagNames = Commons.htmlPurifier(form.getNames()).trim();
        //获取话题的内容以便词频统计
        TopicReplica topic = topicService.getTopicContent(form.getTopic()).orElse(null);
        if (null == topic) {
            model.addAttribute("form", form);
            model.addAttribute("errors", "话题不存在或暂时无法访问");
            return "admin/topic_tag/topic_edit";
        }
        int rates = StringSeekUtils.queryWordCountByBM(topic.getTitle() + " " + topic.getContent().getContent(), newTagNames);
        //
        ActionEventCulpritor aec = AdminHomeController.getActionCulpritor(mbean.getMid(), mbean.getNickname(), request, form.getToken());
        if (topicTagService.create(topic.getId(), newTagNames, rates, aec) > 0) {
            return "redirect:/topic/tag/collection?topic=" + form.getTopic();
        }
        model.addAttribute("form", form);
        model.addAttribute("errors", "增加话题标签操作失败");
        return "admin/topic_tag/topic_edit";
    }
}